package com.alix.paymoney.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ListAdapter;
import android.widget.ListView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by 吴世芊 on 2016/1/4 18:51.
 * 邮箱:apple9302@126.com
 * 公司:浙江答分奇网络技术有限公司
 * 项目名：DaFenQiStudent
 * 包名：com.zhihuitong.dafenqistudent.toolclass
 * 类功能描述：
 */
public class ScreenInfo {
    public static int getWidth(Context context){
        WindowManager manager=(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display=manager.getDefaultDisplay();
        DisplayMetrics outMetrics=new DisplayMetrics();
        display.getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }public static int getHeight(Context context){
        WindowManager manager=(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display=manager.getDefaultDisplay();
        DisplayMetrics outMetrics=new DisplayMetrics();
        display.getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }
    public static Bitmap getCapture(Activity activity) {
        activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
        Bitmap bmp=activity.getWindow().getDecorView().getDrawingCache();
        return bmp;
    }
    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {

        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }
    public static void getMode(Context context){
       WindowManager windowManager= (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = windowManager.getDefaultDisplay();
        DisplayMetrics metrics=new DisplayMetrics();
        int widthPixels = metrics.widthPixels;
        int heightPixels = metrics.heightPixels;
        //真实物理屏幕
        defaultDisplay.getRealMetrics(metrics);
        //内容物理高度
        DisplayMetrics contentMetric=new DisplayMetrics();
        defaultDisplay.getMetrics(contentMetric);

    }
    public static  int getDestiny(Context context){
        WindowManager manager=(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display=manager.getDefaultDisplay();
        DisplayMetrics outMetrics=new DisplayMetrics();
        display.getMetrics(outMetrics);
        return outMetrics.densityDpi;
    }
    public static  int getSdkVersion(){
            return Build.VERSION.SDK_INT;
    }
    public static final String getIMEI(Context context){
        TelephonyManager telephonyManager= (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imei=telephonyManager.getDeviceId();
        return imei;
    }
    private void downloadAudio(final String path) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                MediaPlayer mediaPlayer = new MediaPlayer();
                File file = new File(Environment.getExternalStorageDirectory() + File.separator + "dafenqi/audio");
                if (!file.exists()) {
                    file.mkdirs();
                }
                File fileName = new File(file, "audio.amr");
                if (fileName.exists()) {
                    fileName.delete();
                }
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    InputStream is = conn.getInputStream();
                    final OutputStream os = new FileOutputStream(fileName);
                    byte[] b = new byte[1024 * 1024];
                    int length;
                    Log.e("msg", "下载中" + conn.getInputStream().available());
                    if (conn.getResponseCode() == 200) {
                        while ((length = (is.read(b))) != -1) {
                            os.write(b, 0, length);
                            Log.e("msg", "下载中" + conn.getInputStream().available());
                        }
                        os.flush();
                        is.close();
                        os.close();
                        mediaPlayer.setDataSource(fileName.getAbsolutePath());
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    } else {
                        Log.e("msg", "网络异常");
                    }

                    Log.e("msg", "播放成功");
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("msg", "异常" + e.toString());
                }
            }
        }.start();

    }
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
    public static int getScreenWidth(Context context){
        DisplayMetrics displayMetrics = getDisplayMetrics(context);
        return displayMetrics.widthPixels;
    }
    public static int getScreenHeight(Context context){
        DisplayMetrics displayMetrics = getDisplayMetrics(context);
        return displayMetrics.heightPixels;
    }
    private static DisplayMetrics getDisplayMetrics(Context context){
        WindowManager manager= (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = manager.getDefaultDisplay();
        DisplayMetrics metrics=new DisplayMetrics();
        defaultDisplay.getMetrics(metrics);
        return metrics;
    }
    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param context
     * @param pxValue
     *            （DisplayMetrics类中属性density---像素密度）
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param context
     * @param dipValue
     *            （DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param context
     * @param pxValue
     *            （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param context
     * @param  spValue
     *            （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}
